/*
 * @Description:
 * @Author:hui
 * @Date: 2022-03-24 10:34:44
 * @LastEditTime: 2022-03-31 10:57:45
 */
import store from '@/store/index';
import { getToken,removeToken } from '@/utils/auth';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import router from './router';

const whiteList = [`/login`,'/openfuxing','/carbon/product/index',
  '/carbon/monitoring/view',
	'/product/calendar','carbon/product/detail','carbon/product/calendar']; // no redirect whitelist
NProgress.configure({ 'showSpinner': false });

router.beforeEach(async (to, from, next) => {
	// NProgress.start();
	// // 修改title和favicon
	// changeTitleAndFavicon(to)
	// const hasToken = getToken(`token`);
	// if (hasToken) {
	// 	const userInfo: any = store.state;
	// 	if (!userInfo.user.powerAliasTree) {
	// 		await store
	// 			.dispatch(`user/getUserInfoAction`)
	// 			.then(res => {
	// 				if (res.succ) {
	// 					const { routerList } = userInfo.user;
	// 					router.addRoute({
	// 						'path': `/:pathMatch(.*)*`,
	// 						'redirect': `/404`
	// 					});
	// 					routerList.forEach((r: any) => {
	// 						const obj:any = deepClone(r);
	// 						//处理只有一层级的导航
	// 						if(obj.menuType===`C`&&obj.children.length===0){
	// 							obj.redirect = `${obj.path}Index`
	// 							obj.children = []
	// 							obj.children.push({
	// 								name: `${obj.path.substring(1)}Index`,
	// 								path: `${obj.path}Index`,
	// 								component: loadView(`${obj.path}/index`),
	// 								meta: {
	// 									title: obj.name,
	// 									icon: obj.icon
	// 								}
	// 							})
	// 							r.children = []
	// 						}
	// 						router.addRoute(obj);
	// 					});
	// 					if (!userInfo.user.userInfo.status) {
	// 						next(`/nocertified`);
	// 					} else {
	// 						next({
	// 							...to,
	// 							'replace': true
	// 						});
	// 					}
	// 				}else{
	// 					setTimeout(()=>{
	// 						removeToken(`token`)
	// 						const redirectUri = import.meta.env.VITE_BASE_SSO_URL + `/sso/oauth/logout?redirect_uri=` + window.location.origin;
	// 						window.location.href = redirectUri;
	// 					},400)
	// 				}
	// 			})
	// 			.catch(err => {
	// 				console.log(err);
	// 				NProgress.done();
	// 			});
	// 	} else {
	// 		next();
	// 	}
	// } else  {
	// 	const pageUrl = window.location.origin;
	// 	if (window.location.href.indexOf(`?code=`) > -1) {
	// 		const code = getQueryVariable(`code`);
	// 		await store.dispatch(`user/getCodeToTokenAction`, { 'redirectUri': pageUrl, code });
	// 		if (getToken(`token`)) {
	// 			window.location.href = pageUrl;
	// 		}
	// 	} else {
	// 		const cliendId = import.meta.env.VITE_CLIEND_ID;
	// 		let redirectUri = import.meta.env.VITE_BASE_SSO_URL + `/sso/oauth/authorize`;
	// 		redirectUri = redirectUri + `?response_type=code&client_id=${cliendId}&redirect_uri=` + pageUrl;
	// 		console.log(redirectUri);
	// 		window.location.href = redirectUri;
	// 	}
	// }
	next()
});
router.afterEach(() => {
	NProgress.done();
});

const deepClone =(obj:any)=>{
	　　let objClone =  Array.isArray(obj) ? [] : {};
	　　if (obj && typeof obj === 'object') {
	　　　　for(let key in obj){
	　　　　　　if (obj[key] && typeof obj[key] === 'object'){
	　　　　　　　　objClone[key] = deepClone(obj[key]);
	　　　　　　}else{
	　　　　　　　　objClone[key] = obj[key]
	　　　　　　}
	　　　　}
	　　}
	　　return objClone;
}
const pages = import.meta.globEager(`/src/views/**/*.vue`);
const loadView = (component: string) => {
	const importPage = pages[`/src/views${component}.vue`];
	if (!importPage) {
		throw new Error(`Unknown page ${component}. Is it located under Pages with a .vue extension?`);
	}
	return importPage.default;
};

const changeTitleAndFavicon = (to: any) => {
	document.title = to.meta.title || '数字空间'
	let link = document.querySelector("link[rel*='icon']") || document.createElement('link');
	link.type = 'image/x-icon';
	link.rel = 'shortcut icon';
	link.href = `/${to.meta.icon == 'home' || !to.meta.icon ? 'favicon' : to.meta.icon}.ico`;
	document.getElementsByTagName('head')[0].appendChild(link);
}


const getQueryVariable = (variable: string) => {
	const query = window.location.search.substring(1);
	const vars = query.split(`&`);
	for (let i = 0; i < vars.length; i++) {
		const pair = vars[i].split(`=`);
		if (pair[0] === variable) {
			return pair[1];
		}
	}
	return false;
};